﻿using System;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using System.Net.Sockets;

namespace GeneralDFS.Common.Network
{
    public class IPHelper
    {
        /// <summary>
        /// 获取本地以太网上的IPV4地址
        /// </summary>
        /// <returns>返回本地以太网上的IPV4地址</returns>
        public static string GetLocalIP(String type)
        {
            if (type.ToLower() == "local")
                return "127.0.0.1";
            try
            {
                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    String ipv4Address = "";
                    NetworkInterface[] nic = NetworkInterface.GetAllNetworkInterfaces();
                    for (int i = 0; i < nic.Length; i++)
                    {
                        if (NetworkInterfaceType.Ethernet == nic[i].NetworkInterfaceType)
                        {
                            //获取物理地址
                            PhysicalAddress phyAddress = nic[i].GetPhysicalAddress();
                            //获取IP地址属性
                            IPInterfaceProperties inInter = nic[i].GetIPProperties();
                            //获取单播地址
                            UnicastIPAddressInformationCollection unIpAddress = inInter.UnicastAddresses;
                            //获取多个单播地址
                            IEnumerator<UnicastIPAddressInformation> uipAddInfoEnum = unIpAddress.GetEnumerator();
                            while (uipAddInfoEnum.MoveNext())
                            {
                                //判断是否为IPV4地址
                                if (AddressFamily.InterNetwork == uipAddInfoEnum.Current.Address.AddressFamily)
                                {
                                    ipv4Address = uipAddInfoEnum.Current.Address.ToString();
                                    if(ipv4Address.StartsWith("192.168"))
                                        return ipv4Address;
                                }
                            }
                        }
                    }
                    if ("" == ipv4Address)
                    {
                        LogUtil.LogError("Get local ipv4 address failed!");
                    }

                }
                else
                {
                    LogUtil.LogError("Network is not available!");
                }
            }
            catch (Exception ex)
            {
                LogUtil.LogError(ex.Message);
            }
            return null;
        }
    }
}
